package simple.flow.util;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * web工具类
 *
 * @author lhd
 * @since 2025/4/8 15:26
 */

@Slf4j
public class WebUtil {

    public static void writeResponse(ServletResponse response, int code, Object msg) {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String jsonPrettyStr = JSONUtil.toJsonPrettyStr(JSONUtil.parseObj(msg));
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        OutputStream os = null;
        try {
            os = httpServletResponse.getOutputStream();
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(code);
            os.write(jsonPrettyStr.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取HttpServletResponse
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
}
